import type { Directive } from "@vue/runtime-core";

const vueOutClickClose: Directive = {
  mounted(el, binding): void {
    /**
     * 判断被点击的目标元素是否包含在el(包含该指令的元素)元素里面
     * @param ev 鼠标事件 
     */
    function isOut(ev: MouseEvent): void {
      // 否则关闭对应的操作菜单(binding.value是一个函数用户关闭操作菜单)
      if (!el.contains(ev.target) && binding.value) binding.value(false);
    }
    el.__vueOutClickClose__ = isOut;
    document.addEventListener('click', el.__vueOutClickClose__);
  },
  beforeUnmount(el): void {
    document.removeEventListener('click', el.__vueOutClickClose__);
    Reflect.deleteProperty(el, '__vueOutClickClose__');
  },
};

export default vueOutClickClose